"""
FileName：retry.py
Description：
Author：gaojiahui
Time：2025/8/17 17:49
Website：https://gitee.com/gao-jiahui
"""
import time
from functools import wraps

from utils.exceptions import ElementNotFoundError
from utils.logger import logger

"""重试机制模块"""
def retry_on_failure(max_attempts=3, delay=2, backoff=2,
                     exceptions=(ElementNotFoundError, TimeoutError, AssertionError)):
    """重试机制装饰器"""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            attempts = 0
            current_delay = delay
            while attempts < max_attempts:
                try:
                    return func(*args, **kwargs)
                except exceptions as e:
                    attempts += 1
                    logger.warning(f"尝试 {attempts}/{max_attempts} 失败: {str(e)}")

                    if attempts >= max_attempts:
                        logger.error(f"达到最大重试次数 ({max_attempts}), 标记为失败")
                        raise

                    logger.info(f"等待 {current_delay}秒后重试...")
                    time.sleep(current_delay)
                    current_delay *= backoff # 指数退避
        return wrapper
    return decorator